﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BF.IBLL.BaseSystem;
using Base.Core.UnityFactory;
using BF.Model;
using WebDataControls;
using System.Web.Security;
using BF.Membership.BLL;
using BF.Membership.MembershipEF;
using System.Web.Configuration;
using BF.IBLL.Dictionary;
//using BF.IBLL.HealthResources;

namespace BF.Web.pages.BaseSystem.UserManagement
{
    public partial class UserEdit : BasePage
    {
        #region 实例
        Isys_UserInfoBLL iBLL = IOCFactory.GetIOCResolve<Isys_UserInfoBLL>();
        Idic_OrganizationBLL iOrganizationBLL = IOCFactory.GetIOCResolve<Idic_OrganizationBLL>();
        //Ires_HumanResourcesBLL iBLLHuman = IOCFactory.GetIOCResolve<Ires_HumanResourcesBLL>();
        List<dic_Dict> dicSexList = new List<dic_Dict>();
        #endregion

        #region 页面事件

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindControl();
                BindRoles();
                if (Request.QueryString["sKey"] == null)
                {
                    UserID.Value = "";
                    BandingHosContorl();
                }
                else
                {
                    UserID.Value = Request.QueryString["sKey"].ToString();
                    SetRoles();

                    SetModel(iBLL.GetModelByPK(new Guid(UserID.Value)));

                    sLoginName.Enabled = false;
                    //查看页面
                    if (!String.IsNullOrEmpty(Request.QueryString["State"]) && (Request.QueryString["State"] == "View"))
                    {
                        lbtnReSet.Visible = false;
                        lbtnSave.Visible = false;
                        sLoginName.Enabled = true;
                        sLoginName.ReadOnly = true;
                        btnSeach.Visible = false;
                        sPassword.TextMode = TextBoxMode.SingleLine;
                        EnabledControls(this.Form);
                    }
                }
            }
        }

        /// <summary>
        /// 控制机构相关控件的显示
        /// </summary>
        protected void BandingHosContorl()
        {
            dic_Organization dicModel = iOrganizationBLL.GetModel(GTreeHosKey);
            if (dicModel != null)
            {
                txtHosName.Text = dicModel.sOrganizationName;
                hidHosCode.Value = dicModel.gKey.ToString();
            }
        }

        #region /属性/

        private Guid GTreeHosKey
        {
            get
            {
                if (!string.IsNullOrEmpty(Request.QueryString["gTreeHospitalKey"]))
                {
                    return Guid.Parse(Request.QueryString["gTreeHospitalKey"]);
                }
                else
                {
                    return default(Guid);
                }
            }
        }

        protected string GetTreeHosKey()
        {
            string gTreeHosKey = string.Empty;
            if (GTreeHosKey != default(Guid))
            {
                gTreeHosKey = GTreeHosKey.ToString();
            }
            return gTreeHosKey;
        }

        #endregion

        protected void lbtnSave_Click(object sender, EventArgs e)
        {
            sys_UserInfo model = GetModel(new sys_UserInfo());
            //Guid gHumanKey = string.IsNullOrEmpty(hidgHumanKey.Value) ? default(Guid) : Guid.Parse(hidgHumanKey.Value);
            //res_HumanResources humanModel = iBLLHuman.GetModelByCondition(P => P.gKey == gHumanKey && P.isDel == 0);
            if (Request.QueryString["sKey"] == null)
            {
                if (System.Web.Security.Membership.FindUsersByName(model.sLoginName).Count == 0)
                {
                    if (AddModel(model))
                    {
                        //if (hidType.Value == "1")
                        //{
                        //    humanModel.gUserID = model.gUserID;
                        //    iBLLHuman.Update();
                        //}
                        MessageBox("新增成功！", "function(e){winer.RefurbishParent();Update('" + model.gUserID.ToString() + "','" + GetTreeHosKey() + "');}");
                    }
                    else
                    {
                        Messages("新增失败！");
                    }
                }
                else
                {
                    Messages("用户名已存在!", this.Updatepanel1);
                }
            }
            else
            {
                if (UpdateModel())
                {
                    Messages("修改成功！", "function(e){winer.RefurbishParent();}", this.Updatepanel1);
                }
                else
                {
                    Messages("修改失败！");
                }
            }
        }

        #endregion

        #region 自定义方法

        private void BindControl()
        {
            System.Web.UI.WebControls.ListItem li = new System.Web.UI.WebControls.ListItem
            {
                Value = "",
                Text = "--请选择--"
            };

            //绑定机构类型
            if (iSex == null || dicSexList.Count == 0)
                dicSexList = GetDictList("sSexCode");
            this.iSex.DataSource = dicSexList;
            this.iSex.DataValueField = "sCode";
            this.iSex.DataTextField = "sName";
            this.iSex.DataBind();
            this.iSex.Items.Insert(0, li);

        }

        private sys_UserInfo GetOldModel()
        {
            sys_UserInfo model = iBLL.GetModelByPK(new Guid(UserID.Value));
            return model;
        }

        /// <summary>
        /// 获得用户对应的角色
        /// </summary>
        /// <param name="roles"></param>
        private void GetRoles(List<String> roles)
        {
            roles.Clear();
            roles.AddRange(from ListItem rolebox in UserRoles.Items where rolebox.Selected select rolebox.Value);
        }


        private void SetModel(sys_UserInfo model)
        {
            //if (model.res_HumanResources.FirstOrDefault() != null)
            //{
            //    btnSeach.Visible = false;
            //    btnCheckHuman.Visible = false;
            //}
            WebUIHelper.SetControlsValue(model, "sys_UserInfo", this.Form);
            hidHosCode.Value = model.gOrganizationKey == null ? "" : model.gOrganizationKey.ToString();
            UserID.Value = model.gUserID.ToString();
            if (!string.IsNullOrEmpty(sPassword.Text.Trim()))
            {
                sPassword.Attributes["value"] = sPassword.Text;
                sPassword.Attributes["value"] = sPassword.Text;
            }
            if (model.gOrganizationKey != null)
            {
                dic_Organization hospital = iOrganizationBLL.GetModel(new Guid(model.gOrganizationKey.ToString()));
                txtHosName.Text = hospital == null ? "" : hospital.sOrganizationName;
            }
        }
        #region 根据用户绑定已角色
        private void SetRoles()
        {

            sys_UserInfo model = GetOldModel();

            foreach (ListItem checkbox in UserRoles.Items)
            {
                checkbox.Selected = false;
            }
            string[] userRoles = Roles.GetRolesForUser(model.sLoginName);
            foreach (string role in userRoles)
            {
                ListItem checkbox = UserRoles.Items.FindByValue(role);
                if (checkbox == null) continue;
                checkbox.Selected = true;
            }
            isapproved.Checked = System.Web.Security.Membership.GetUser(model.sLoginName) == null ? false : System.Web.Security.Membership.GetUser(model.sLoginName).IsApproved;

        }

        #endregion

        #region 绑定角色用户控件
        protected void BindRoles()
        {
            string[] list = null;

            list = Roles.GetRolesForUser(GetSessionCurrentUserInfo.sLoginName);

            if (GetSessionCurrentUserInfo.sLoginName.ToLower() == "admin")
            {
                list = Roles.GetAllRoles();
            }
            foreach (string val in list)
            {
                string subVal = val.Length > 6 ? val.Substring(0, 6) + "…" : val;
                ListItem item = new ListItem(subVal);
                item.Value = val;
                item.Attributes.Add("style", "display:block;width:117px;float:left;");
                item.Attributes.Add("onmouseover", "ShowToolTip(event,'" + val + "')");
                UserRoles.Items.Add(item);
            }

            //UserRoles.DataSource = list;
            //UserRoles.DataBind();
        }
        #endregion

        private sys_UserInfo GetModel(sys_UserInfo model)
        {
            model = (sys_UserInfo)WebUIHelper.GetControlsModel(model, "sys_UserInfo", this.Form);
            model.gOrganizationKey = new Guid(hidHosCode.Value);
            return model ?? new sys_UserInfo();
        }

        private bool AddModel(sys_UserInfo model)
        {
            model.iState = isapproved.Checked;
            model.gOrganizationKey = new Guid(hidHosCode.Value);
            List<String> roles = new List<string>();
            GetRoles(roles);
            return iBLL.Add(model, roles, isapproved.Checked);
        }

        private bool UpdateModel()
        {
            sys_UserInfo model = GetModel(iBLL.GetModelByPK(new Guid(UserID.Value)));
            //model.gUserID = new Guid(UserID.Value);
            if (sLoginName.Text != "admin")
            {
                model.gOrganizationKey = new Guid(hidHosCode.Value);
            }
            List<String> roles = new List<string>();
            GetRoles(roles);
            if (hidType.Value == "1")
            {
                Guid gHumanKey = string.IsNullOrEmpty(hidgHumanKey.Value) ? default(Guid) : Guid.Parse(hidgHumanKey.Value);
                //res_HumanResources humanModel = iBLLHuman.GetModelByCondition(P => P.gKey == gHumanKey && P.isDel == 0);
                return iBLL.Update(model, roles, isapproved.Checked);
            }
            else
            {
                return iBLL.Update(model, roles, isapproved.Checked);
            }
        }
        #endregion

        protected void btnCheckHuman_Click(object sender, EventArgs e)
        {
            //if (String.IsNullOrEmpty(Request.QueryString["sKey"]))
            //{
            //    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "click", "OpenImportHumanList();", true);
            //}
            //else
            //{
            //    Guid gKey = Guid.Parse(Request.QueryString["sKey"]);
            //    //res_HumanResources humanModel = iBLLHuman.GetModelByCondition(P => P.gUserID == gKey && P.isDel == 0);
            //    if (humanModel != null)
            //    {
            //        Messages("当前人员已绑定人力资源信息，无法再次绑定！");
            //    }
            //    else
            //    {
            //        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "click", "OpenImportHumanList();", true);
            //    }
            //}
        }
    }
}